<template>
  <div>
    <n-space vertical>
      <n-button type="primary" @click="showModal = true">添加推送配置</n-button>

      <n-data-table
        :columns="columns"
        :data="pushList"
        :pagination="pagination"
      />
    </n-space>

    <n-modal
      v-model:show="showModal"
      preset="dialog"
      :title="isEditMode ? '编辑推送配置' : '添加推送配置'"
      :mask-closable="false"
      :closable="true"
      :auto-focus="false"
      style="width: 600px"
    >
      <template #header>
        <div class="modal-header">
          {{ isEditMode ? '编辑推送配置' : '添加推送配置' }}
        </div>
      </template>

      <n-form
        :model="formValue"
        :rules="rules"
        ref="formRef"
        label-placement="left"
        label-width="auto"
        size="medium"
      >
        <!-- 原有表单内容保持不变 -->
      </n-form>

      <template #action>
        <n-space>
          <n-button @click="showModal = false">取消</n-button>
          <n-button type="primary" @click="handleSubmit" :loading="submitting">
            {{ isEditMode ? '更新' : '提交' }}
          </n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
import {ref, reactive, h,onMounted} from 'vue'
import {NButton, useMessage,FormInst} from 'naive-ui'
import {editPushConfig,addPushConfig, getPushConfigList, PushConfig} from "@/api/setting/system";

const message = useMessage()
const showModal = ref(false)
const formRef = ref<FormInst | null>(null)
const pushList = ref<PushConfig[]>([])
const isEditMode = ref(false)
const submitting = ref(false)

// 添加 resetForm 方法
const resetForm = () => {
  Object.assign(formValue, {
    key: null,
    name: '',
    storageType: '',
    pushUrl: '',
    accessKey: '',
    status: true
  })
  isEditMode.value = false
}

const formValue = reactive({
  ID: null,
  Name: '',
  PushType: '',
  PushUrl: '',
  AccessKey: '',
  SecretKey: '',
  Enable: true,
  Remark: ''
})
const rules = {
    name: {
      required: true,
      trigger: ['blur', 'input'],
      validator: (_, value, callback) => {
        if (!value) {
          return callback(new Error('请输入配置名称'))
        }
        if (value.length > 30) {
          return callback(new Error('名称长度不能超过30个字符'))
        }
        if (!/^[\u4e00-\u9fa5a-zA-Z0-9_-]+$/.test(value)) {
          return callback(new Error('名称只能包含中文、英文、数字、下划线和横线'))
        }
        callback()
      }
    },
    endpoint: {
      required: true,
      trigger: ['blur', 'input'],
      validator: (_, value, callback) => {
        if (!value) {
          return callback(new Error('请输入接口地址'))
        }
        const urlPattern = /^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/i
        if (!urlPattern.test(value)) {
          return callback(new Error('请输入有效的URL地址(需包含http://或https://)'))
        }
        callback()
      }
    },
  }

const columns = [
  {
    title: 'ID',
    key: 'ID'
  },
  {
    title: '配置名称',
    key: 'Name'
  },
  {
    title: '接口地址',
    key: 'PushUrl'
  },
  {
    title: '描述信息',
    key: 'Remark'
  },
  {
    title: '状态',
    key: 'Enable',
    render(row) {
      return row.status ? '启用' : '禁用'
    }
  },
  {
    title: '操作',
    key: 'actions',
    render(row) {
      return [
        h(
          NButton,
          {
            size: 'small',
            onClick: () => handleEdit(row)
          },
          { default: () => '编辑' }
        ),
        h(
          NButton,
          {
            size: 'small',
            style: 'margin-left: 5px',
            onClick: () => handleDelete(row.key)
          },
          { default: () => '删除' }
        )
      ]
    }
  }
]

const pagination = reactive({
  page: 1,
  pageSize: 10
})

const handleEdit = (row) => {
  Object.assign(formValue, row)
  showModal.value = true
  isEditMode.value = true
}

const handleDelete = (id) => {
  pushList.value = pushList.value.filter(item => item.ID !== id)
  message.success('删除成功')
}

const handleSubmit = (e) => {
  e.preventDefault()
  formRef.value?.validate((errors) => {
    submitting.value = true
    const apiCall = isEditMode.value
      ? editPushConfig(id, formValue )
      : addPushConfig(formValue)

    apiCall.then(res => {
      message.success(isEditMode.value ? '更新成功' : '添加成功')
      showModal.value = false
      resetForm()
      loadPushConfigs() // 重新加载数据
    }).catch(error => {
      message.error('操作失败: ' + error.message)
    }).finally(() => {
      submitting.value = false
    })
  })

}

// 添加加载推送配置的方法
const loadPushConfigs = async () => {
  try {
    const res = getPushConfigList()
    console.log("==============="+res)
    // pushList.value = res || []

    pushList.value=[
      {
        ID: 1,
        Name: 'Http推送',
        PushType: 'local',
        PushUrl: 'http://api.fionsiot.com/xx/x',
        AccessKey: '',
        SecretKey: '',
        Enable: true,
        Remark: 'Http推送测试'
      },
      {
        ID: 1,
        Name: 'Mqtt推送',
        PushType: 'mqtt',
        PushUrl: 'tcp://api.fionsiot.com',
        AccessKey: 'xxxx',
        SecretKey: 'xxxxxxxxxxxxxxxxxxxxxxx',
        Enable: true,
        Remark: 'Mqtt推送测试'
      },
    ]
  } catch (error) {
    message.error('加载推送配置失败')
  }
}

onMounted(() => {
  loadPushConfigs()
})

</script>

<style scoped>
.n-button {
  margin-bottom: 20px;
}
</style>
